package com.zf.museum.service.impl;

import com.zf.museum.model.*;
import com.zf.museum.repository.RecordRepository;
import com.zf.museum.repository.UserRepository;
import com.zf.museum.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class RecordServiceImpl implements RecordService{

    @Autowired
    private RecordRepository recordRepository;
    @Autowired
    private UserRepository userRepository;

    @Override
    public void addMulti(MultiChoices multiChoices, String openId) {

        Record record = getRecord(openId);
        Set<MultiChoices> multiChoices1 = record.getMultiChoices();
        multiChoices1.add(multiChoices);
        record.setMultiChoices(multiChoices1);
        recordRepository.save(record);
    }

    @Override
    public void addSingle(SingleChoice singleChoice, String openId) {

        Record record = getRecord(openId);
        Set<SingleChoice> singleChoices1 = record.getSingleChoices();
        singleChoices1.add(singleChoice);
        record.setSingleChoices(singleChoices1);
        recordRepository.save(record);
    }

    @Override
    public void addTfng(Tfng tfng, String openId) {

        Record record = getRecord(openId);
        Set<Tfng> tfngs1 = record.getTfngs();
        tfngs1.add(tfng);
        recordRepository.save(record);
    }

    @Override
    public Record getRecord(String openId) {

        User user = userRepository.getUserByOpenId(openId);
        Record record = recordRepository.getRecordByUser(user);
        if (record == null) {
            record = new Record();
            Set<MultiChoices> multiChoices = new HashSet<>();
            Set<SingleChoice> singleChoices = new HashSet<>();
            Set<Tfng> tfngs = new HashSet<>();
            record.setUser(user);
            record.setMultiChoices(multiChoices);
            record.setSingleChoices(singleChoices);
            record.setTfngs(tfngs);
        }
        return record;
    }

    @Override
    public List<Record> getAll() {

        return recordRepository.findAll();
    }
}
